#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun  7 15:29:11 2023

@author: jcfq2
"""

import matplotlib.pyplot as plt
# import matplotlib.ticker as mticker
import numpy as np
# import shapely.geometry as sgeom
# from cartopy.feature import ShapelyFeature
from scipy.io import readsav
import cartopy.crs as ccrs
from matplotlib.colors import PowerNorm
from matplotlib import patheffects

import io
import sys
import os

sys.path.insert(0, '../../planetary_values')

print(sys.path)
from planet_magfield import Bmag


from grille_vogt_localtime_dawndusk_all import load_vogt_slices
from grille_vogt_localtime_dawndusk_all import vogt_ofl
from grille_vogt_localtime_dawndusk_all import fit_fieldline_fixed
from grille_vogt_localtime_dawndusk_all import fit_fieldline_scattered

sys.path.insert(0, '../../tss')
from basic.polygonmask import maskeqvalue
from basic.polygonmask import masksubarray
from basic.interpolate_irregular import data_atlatlong


def apply_gamma_correction(array, gamma=1.0):
    # Normalize the array values to [0, 1] range
    array_normalized = (array - np.min(array)) / (np.max(array) - np.min(array))
    # Apply gamma correction using PowerNorm
    corrected_array = PowerNorm(gamma)(array_normalized)
    # Rescale the values back to the original range
    corrected_array = corrected_array * (np.max(array) - np.min(array)) + np.min(array)
    return corrected_array


# In[0]
# set up values


maxint=1.9
minint=0.1
mincount=0
maxcount=100.#3.*3600#hours - many hours due to bleeding of individual pixels across multiple bins
mindate=0
maxdate=30

minrange=0.6
maxrange=1.4
# minrange=0.0003
# maxrange=0.0018;0.0001
xxrange=6
startx=1

polelat=90
polelong=180


# In[1]
# load data


results='/Users/jcfq2/OneDrive - Northumbria University - Production Azure AD/results/'
planetary='/Users/jcfq2/OneDrive - Northumbria University - Production Azure AD/python/planetary_values/'


idl_file = readsav(results+'jupimage_phase_total_crazytown.idl')
# idl_file = readsav(results+'jupimage_phase_total_crazytown_avgclicks.idl')
# idl_file = readsav(results+'jupimage_phase_total_crazytown_avgclicks.idl')
a=idl_file['a']
a2=idl_file['a2']
b=idl_file['b']
b2=idl_file['b2']

aa=a
aa2=a2
bb=b
bb2=b2


ab=a/b
ab=np.nan_to_num(ab)



idl_file_date = readsav(results+'jupimage_phase_datecount.idl')
datecount = idl_file_date['datecount']

   # In[3] set up vogt


# for cml in range(50,329,10):

               


# In[4] 

totalmap=np.sum(ab,axis=0)
# plt.imshow(totalmap)
# plt.show()

totalmapN=totalmap
totalmapS=totalmap
totalmapN[0:70,:]=0
totalmapS[90:,:]=0

totalmap=totalmap/np.mean(totalmap)
totalmapN=totalmapN/np.mean(totalmapN)
totalmapS=totalmapS/np.mean(totalmapS)

lon = np.linspace(360, 0, 360)
lat = np.linspace(-90, 90, 181)
lon2d, lat2d = np.meshgrid(lon, lat)


crs = ccrs.RotatedPole(globe=ccrs.Globe(flattening=(0.0)))














# In[4]
sys.path.insert(0, '../../planetary_values')
   
ofl_lat,ofl_lon=vogt_ofl()
    
subsolarlat=0
subsolarlongitude=180#240.3#+180


s_ssl=str(int(subsolarlongitude/10+1)*10)

# print(s_ssl)

sys.path.insert(0, '../../planetary_values')

v = open(os.path.join(sys.path[0],'fieldline_tracing/fieldline_tracing_mapping_contours_kk2009ext_jrm09int_north_sslong'+s_ssl+'.txt'))
north_plotting = np.zeros([28,36,4])

header = v.readline()

for z in range(28):
    for y in range(36):
        line = v.readline()
        north_plotting[z,y,0]=line[0:12]
        north_plotting[z,y,1]=line[14:20]
        null1=line[21:29]
        if any(chr.isdigit() for chr in null1):
            north_plotting[z,y,2]=null1
        else:
            north_plotting[z,y,2]=np.nan
        null2=line[30:38]
        if any(chr.isdigit() for chr in null2):
            north_plotting[z,y,3]=null2
        else:
            north_plotting[z,y,3]=np.nan



# In[4]
sys.path.insert(0, '../../planetary_values')
   
# ofl_lat,ofl_lon=vogt_ofl()
    
subsolarlat=0
subsolarlongitude=180#240.3#+180


s_ssl=str(int(subsolarlongitude/10+1)*10)

# print(s_ssl)

sys.path.insert(0, '../../planetary_values')



median_switch='True'
median_switch='False'


##### correct for B field and PLT

mapfull=ab*1.


B1=Bmag(lon2d, lat2d,radial=False)
ax0=1120.572303190426
ax1=-43.641738021841704#g.parameters[0]


pax0=-7.176710984602767e-06
pax1=1.9448120666675136e-06
pax2=-8.31558916098032e-08

paxm=3.188967985006459e-06


i=1
mapshape=np.sum(mapfull[75+i*30:75+(i+1)*30,:,:],axis=0)    

scaleBint=B1*ax1+ax0

scaleBint=scaleBint/np.mean(scaleBint)

scaleBint=np.reshape(scaleBint,mapshape.shape)

# plt.plot(scaleBint[:,90])
# plt.show()
P_LT = np.arange(6,18,0.01)

PLT_CORR = (pax0 + P_LT*pax1 + P_LT**2*pax2) / paxm

# plt.plot(P_LT,PLT_CORR)

for lt in range (0,360,1):
    # print(lt)
    # plt.imshow(mapfull[lt,:,:])
    # plt.show()
    mapfull[lt,:,:] = mapfull[lt,:,:]/ (scaleBint * ((pax0 + (lt/360*24)*pax1 + (lt/360*24)**2*pax2) / paxm))
    # plt.imshow(mapfull[lt,:,:])
    # plt.show()



#### now normalise the intensity back to the median of the auroral region only
# 
# 
# 

np_lon2=north_plotting[1,:,3]
np_lat2=north_plotting[1,:,2]
np_loc2=north_plotting[1,:,1]
   

np_lon13=north_plotting[13,:,3]
np_lat13=north_plotting[13,:,2]
np_loc13=north_plotting[13,:,1]


fit_xmo,fit_ymo=fit_fieldline_fixed(np_lon2,np_lat2) 
fit_xmo2,fit_ymo2=fit_fieldline_fixed(np_lon13,np_lat13) 
fity,fitx = fit_fieldline_scattered(ofl_lon,ofl_lat,sigma=6)
# polar aurora should be included - we just want to measure total auroral brightness - teh shaping is necessary to remove pixel flaring
# no- they should be done separately!

mapmap=np.sum(mapfull[75:75+(5+1)*30,:,:],axis=0)/(30*6)

# mapmap[170:,:]=0


mapmap2,lon2d2,lat2d2=masksubarray(lon2d,lat2d,mapmap,fit_xmo,fit_ymo)

nonzerovals=np.nonzero(mapmap2)

mapmap3=mapmap2[nonzerovals]
lon2d3=lon2d2[nonzerovals]
lat2d3=lat2d2[nonzerovals]




mapmap4me,lon2d4me,lat2d4me=masksubarray(lon2d3,lat2d3,mapmap3,fit_xmo2,fit_ymo2,invert=True)

total_me_bright=np.median(mapmap4me)
print(total_me_bright)

mapfull = mapfull/total_me_bright



# i=4
# # mapmap=np.median(mapfull[75+i*30:75+(i+1)*30,:,:],axis=0)


# if median_switch == 'True':
#     mapmap=np.median(mapfull[75+i*30:75+(i+1)*30,:,:],axis=0)
# else:            
#     mapmap=np.mean(mapfull[75+i*30:75+(i+1)*30,:,:],axis=0)

# if median_switch == 'True':
#     mapmapT=np.median(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)
# else:            
#     mapmapT=np.mean(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)

# # mapmapT=np.sum(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)
# # mapmap=mapmap/np.mean(np.nonzero(mapmapT))
# # mapmapT=mapmapT/np.mean(np.nonzero(mapmapT))
# mapmap_diff=(mapmap)/(mapmapT)
   



# plt.imshow(mapmap, norm=PowerNorm(gamma=0.5, vmin=minint, vmax=maxint) )
# plt.show()

# plt.imshow(mapmap_diff,cmap='RdBu',vmax=maxrange,vmin=minrange)
# plt.show()


# phasemap=np.sum(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)/(30*5)/0.5e1
# # phasemap[75+i*30:75+(i+1)*30,:]=phasemap[75+i*30:75+(i+1)*30,:]*1e1
# phasemap[:,75+i*30:75+(i+1)*30]=phasemap[:,75+i*30:75+(i+1)*30]*0.5e1

# plt.imshow(phasemap,cmap='afmhot', norm=PowerNorm(gamma=0.5, vmin=minint, vmax=maxint) )
# plt.show()

# scaling= 0.5
# fig_temp = plt.figure(figsize=(10*scaling,10*scaling),dpi=100,facecolor='k')

# # io_buf = io.BytesIO()

# ax_temp = plt.subplot(1,1,1,projection=ccrs.Orthographic(360-polelong, polelat))
# ax_temp.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())





# #### a3x1 = plt.subplot(1, 1, 1,projection=ccrs.Orthographic(360-polelong, polelat))
# #### gl = a3x1.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.5, linestyle='dotted', draw_labels=False)

# # gl = ax1.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)

# # cc1=ax_temp.contourf(lon2d, lat2d, mapmap,transform=ccrs.PlateCarree(),levels=256,cmap='afmhot', norm=PowerNorm(gamma=0.5, vmin=minint, vmax=maxint) )
# cc1=ax_temp.contourf(lon2d, lat2d, mapmap,transform=ccrs.PlateCarree(),levels=256,cmap='afmhot', vmin=minint, vmax=maxint )







# window_extent = ax_temp.get_window_extent()
# fig_temp.savefig(io_buf, format='raw', bbox_inches='tight', pad_inches=0)
# io_buf.seek(0)

# img_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),
                  # newshape=(int(window_extent.height), int(window_extent.width), -1))
 



# In[5]
brightness=np.zeros([xxrange,36])
brightness_diff=np.zeros([xxrange,36])
brightness_diff2=np.zeros([xxrange,36])

lt_text=['08h','10h','12h','14h','16h']
# for i in range(startx,xxrange+2):

    


for i in range(startx,xxrange):
# for i in range(startx+3,startx+4):

    

    # cml=360-(75+i*30+15)    
    cml=360-(90+i*20+10)   
    
    
    subsolarlat=0
    subsolarlongitude=cml#240.3#+180
    
    
    s_ssl=str(int(subsolarlongitude/10+1)*10)
    
    # print(s_ssl)
    
    
    v = open(planetary+'fieldline_tracing/fieldline_tracing_mapping_contours_kk2009ext_jrm09int_north_sslong'+s_ssl+'.txt')
    north_plotting = np.zeros([28,36,4])
    
    header = v.readline()
    
    for z in range(28):
        for y in range(36):
            line = v.readline()
            north_plotting[z,y,0]=line[0:12]
            north_plotting[z,y,1]=line[14:20]
            null1=line[21:29]
            if any(chr.isdigit() for chr in null1):
                north_plotting[z,y,2]=null1
            else:
                north_plotting[z,y,2]=np.nan
            null2=line[30:38]
            if any(chr.isdigit() for chr in null2):
                north_plotting[z,y,3]=null2
            else:
                north_plotting[z,y,3]=np.nan



    # mapmap=np.sum(mapfull[90+i*20:90+(i+1)*20,:,:],axis=0)

    # if median_switch == 'True':
    #     mapmap=np.median(mapfull[75+i*30:75+(i+1)*30,:,:],axis=0)
    # else:            
    #     mapmap=np.mean(mapfull[75+i*30:75+(i+1)*30,:,:],axis=0)

    # if median_switch == 'True':
    #     mapmapT=np.median(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)
    # else:            
    #     mapmapT=np.mean(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)

    # # mapmapT=np.sum(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)
    # # mapmap=mapmap/np.mean(np.nonzero(mapmapT))
    # # mapmapT=mapmapT/np.mean(np.nonzero(mapmapT))
    # mapmap_diff=(mapmap)/(mapmapT)
    
    
    # mapmap[180,:]=maxint
 
    # countmap=np.sum(b[75+i*30:75+(i+1)*30,:,:],axis=0)
    # totalmap3=np.sum(a[75+i*30:75+(i+1)*30,:,:],axis=0)
    
    
    
    
    

    # countmap = np.sum(b[75+i*30:75+(i+1)*30,:,:],axis=0)/3600 #in hours
    # countmap2 = np.sum(b2[75+i*30:75+(i+1)*30,:,:],axis=0)/3600 #in hours
    
    
    # countmapN = countmap.copy()
    # countmapS = countmap.copy()
    # countmapN[0:70,:] = 0
    # countmapS[90:,:] = 0

    # countmapN2 = countmap2.copy()
    # countmapS2 = countmap2.copy()
    # countmapN2[0:70,:] = 0
    # countmapS2[90:,:] = 0

    # totalmap3 = np.sum(a[:, :, 75 + i * 30 : 75 + (i + 1) * 30], axis=2)

    # totalmapN3 = totalmap3.copy()
    # totalmapS3 = totalmap3.copy()
    # totalmapN3[0:70,:] = 0
    # totalmapS3[90:,:] = 0

    # totalmapN3 = totalmapN3 / np.mean(totalmapN3)
    # totalmapS3 = totalmapS3 / np.mean(totalmapS3)
    # totalmap3 = totalmap3 / np.mean(totalmap3)




    # datemap=datecount[i-1,:,:]+0.00001 # so... datamap fails, perhaps because all the values are float-integers.. adding a chugum helps


    mapfull=ab

    # mapmap=np.sum(mapfull[90+i*20:90+(i+1)*20,:,:],axis=0)
    mapmap=np.sum(mapfull[75+i*30:75+(i+1)*30,:,:],axis=0)
    mapmapT=np.sum(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)
    mapmap=mapmap/np.mean(np.nonzero(mapmapT))
    mapmapT=mapmapT/np.mean(np.nonzero(mapmapT))
    mapmap_diff=(mapmap*5)/(mapmapT)
    
    
    mapmap[180,:]=maxint
 
    # countmap=np.sum(b[75+i*30:75+(i+1)*30,:,:],axis=0)
    totalmap3=np.sum(a[75+i*30:75+(i+1)*30,:,:],axis=0)
    
    
    

    countmap = np.sum(b[75+i*30:75+(i+1)*30,:,:],axis=0)/3600 #in hours
    countmap2 = np.sum(b2[75+i*30:75+(i+1)*30,:,:],axis=0)/3600 #in hours
    
    
    countmapN = countmap.copy()
    countmapS = countmap.copy()
    countmapN[0:70,:] = 0
    countmapS[90:,:] = 0

    countmapN2 = countmap2.copy()
    countmapS2 = countmap2.copy()
    countmapN2[0:70,:] = 0
    countmapS2[90:,:] = 0

    totalmap3 = np.sum(a[:, :, 75 + i * 30 : 75 + (i + 1) * 30], axis=2)

    totalmapN3 = totalmap3.copy()
    totalmapS3 = totalmap3.copy()
    totalmapN3[0:70,:] = 0
    totalmapS3[90:,:] = 0

    totalmapN3 = totalmapN3 / np.mean(totalmapN3)
    totalmapS3 = totalmapS3 / np.mean(totalmapS3)
    totalmap3 = totalmap3 / np.mean(totalmap3)




    datemap=datecount[i-1,:,:]+0.00001 # so... datamap fails, perhaps because all the values are float-integers.. adding a chugum helps

    print(i,(4*(i-1)))


############## save the intensity

    scaling= 0.5
    fig_temp = plt.figure(figsize=(10*scaling,10*scaling),dpi=100,facecolor='k')

    io_buf = io.BytesIO()
    
    ax_temp = plt.subplot(1,1,1,projection=ccrs.Orthographic(360-polelong, polelat))
    ax_temp.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())

    #### a3x1 = plt.subplot(1, 1, 1,projection=ccrs.Orthographic(360-polelong, polelat))
    #### gl = a3x1.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.5, linestyle='dotted', draw_labels=False)

    # gl = ax1.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)

    cc1=ax_temp.contourf(lon2d, lat2d, mapmap,transform=ccrs.PlateCarree(),levels=256,cmap='afmhot', norm=PowerNorm(gamma=0.5, vmin=minint, vmax=maxint) )
    # cc1=ax_temp.contourf(lon2d, lat2d, mapmap,transform=ccrs.PlateCarree(),levels=256,cmap='afmhot', vmin=minint, vmax=maxint )
    
    window_extent = ax_temp.get_window_extent()
    fig_temp.savefig(io_buf, format='raw', bbox_inches='tight', pad_inches=0)
    io_buf.seek(0)

    img_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),
                      newshape=(int(window_extent.height), int(window_extent.width), -1))
 


############## save the brightness diff
    
    
    mapmap_diff[mapmap_diff>maxrange]=maxrange
    mapmap_diff[mapmap_diff<minrange]=minrange

    #     cc2=ax2.contourf(lon2d, lat2d, mapmap_diff,transform=ccrs.PlateCarree(),levels=128,cmap='RdBu',vmax=maxrange,vmin=minrange) 

    scaling= 1
    fig_temp = plt.figure(figsize=(10*scaling,10*scaling),dpi=100,facecolor='k')

    io_buf = io.BytesIO()
    
    ax_temp = plt.subplot(1,1,1,projection=ccrs.Orthographic(360-polelong, polelat))
    ax_temp.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())

    #### a3x1 = plt.subplot(1, 1, 1,projection=ccrs.Orthographic(360-polelong, polelat))
    #### gl = a3x1.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.5, linestyle='dotted', draw_labels=False)

    # gl = ax1.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)

    cc2=ax_temp.contourf(lon2d, lat2d, mapmap_diff,transform=ccrs.PlateCarree(),levels=256,cmap='RdBu_r',vmax=maxrange,vmin=minrange)
    
    window_extent = ax_temp.get_window_extent()
    fig_temp.savefig(io_buf, format='raw', bbox_inches='tight', pad_inches=0)
    io_buf.seek(0)

    diff_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),
                      newshape=(int(window_extent.height), int(window_extent.width), -1))





    phasemap=np.sum(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)/(30*5)/0.15e1
    # phasemap[75+i*30:75+(i+1)*30,:]=phasemap[75+i*30:75+(i+1)*30,:]*1e1
    phasemap[:,75+i*30:75+(i+1)*30]=phasemap[:,75+i*30:75+(i+1)*30]*0.5e1


    scaling= 1
    fig_temp = plt.figure(figsize=(10*scaling,10*scaling),dpi=100,facecolor='k')

    io_buf = io.BytesIO()

    
    ax_temp = plt.subplot(1,1,1,projection=ccrs.Orthographic(360-polelong, 0))
    # ax_temp.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())

    #### a3x1 = plt.subplot(1, 1, 1,projection=ccrs.Orthographic(360-polelong, polelat))
    #### gl = a3x1.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.5, linestyle='dotted', draw_labels=False)

    # gl = ax1.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)

    cc5=ax_temp.contourf(lon2d, lat2d, phasemap,transform=ccrs.PlateCarree(),levels=256,cmap='afmhot', norm=PowerNorm(gamma=0.5, vmin=minint*3, vmax=maxint*4) )
    
    window_extent = ax_temp.get_window_extent()
    fig_temp.savefig(io_buf, format='raw', bbox_inches='tight', pad_inches=0)
    io_buf.seek(0)

    lt_arr = np.reshape(np.frombuffer(io_buf.getvalue(), dtype=np.uint8),
                      newshape=(int(window_extent.height), int(window_extent.width), -1))



#####################

    # img_arr = lt_arr
    # diff_arr = img_arr 
    # lt_arr = img_arr



    # gl.xlocator = mticker.FixedLocator(np.arange(18)*20-180)
    # gl.ylocator = mticker.FixedLocator(np.arange(9)*20-90)


    
    if i == 1:
        int_1 = img_arr
        diff_1 = diff_arr
        lt_1 = lt_arr
        
    if i == 2:
        int_2 = img_arr
        diff_2 = diff_arr
        lt_2 = lt_arr

    if i == 3:
        int_3 = img_arr
        diff_3 = diff_arr
        lt_3 = lt_arr

    if i == 4:
        int_4 = img_arr
        diff_4 = diff_arr
        lt_4 = lt_arr

    if i == 5:
        int_5 = img_arr
        diff_5 = diff_arr
        lt_5 = lt_arr



# %%





fig=plt.figure()




#old ratio is 5:5.33
#new ratio is 5:3.33
fig.set_figwidth(11)
fig.set_figheight(11/4*5)
fig.set_dpi(72)
fig.subplots_adjust(wspace=0, hspace=0)

# for i in range(startx+2,startx+3):



# cml=360-(75+i*30+15)    

for i in range(startx,xxrange):
    cml=360-(90+i*20+10)   
    
    
    subsolarlat=0
    subsolarlongitude=cml#240.3#+180
    
    
    s_ssl=str(int(subsolarlongitude/10+1)*10)
    


    print(i,(4*(i-1)))



    if i == 1:
        int_x = int_1
        diff_x = diff_1
        lt_x = lt_1
        
    if i == 2:
        int_x = int_2
        diff_x = diff_2
        lt_x = lt_2
        
    if i == 3:
        int_x = int_3
        diff_x = diff_3
        lt_x = lt_3

    if i == 4:
        int_x = int_4
        diff_x = diff_4
        lt_x = lt_4

    if i == 5:
        int_x = int_5
        diff_x = diff_5
        lt_x = lt_5

 
    # ax1 = plt.subplot(1, 7, 8-i,projection=ccrs.Orthographic(360-polelong, polelat))
    ax1_base = plt.subplot(5, 4, (4*(5-i))+1,projection=ccrs.Orthographic(360-polelong, polelat))
    gl = ax1_base.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)

    # ax1_img = plt.subplot(5, 4, (4*(5-i))+1)
    ax1_chartBox = ax1_base.get_position()
    ax1_img = fig.add_axes([ax1_chartBox.x0, ax1_chartBox.y0, 
                 ax1_chartBox.width, 
                 ax1_chartBox.height], transform=ax1_base.transAxes, frameon=False) 
    ax1_img.set_axis_off()
    fig.set_facecolor("white")
    
    ax1_img.imshow(int_x)

    ax1 = fig.add_axes([ax1_chartBox.x0, ax1_chartBox.y0, 
                      ax1_chartBox.width, 
                      ax1_chartBox.height], transform=ax1_base.transAxes,projection=ccrs.Orthographic(360-polelong, polelat), frameon=False) 
    
    # if i == 5 | i == 1:



    # cc1=ax1.contourf(lon2d, lat2d, mapmap,transform=ccrs.PlateCarree(),levels=128,cmap='afmhot', norm=PowerNorm(gamma=0.5, vmin=0.1, vmax=maxint) )
    # ax1_window_extent = ax1.get_window_extent()
    # ax1_chartBox = ax1.get_position() 
    # a1_img=plt.subplot(1,1,1)
    # a1_img.set_position([ax1_chartBox.x0, ax1_chartBox.y0, 
    #              ax1_chartBox.width, 
    #              ax1_chartBox.height])
 
    
    # ax1 = plt.subplot(5, 4, (4*(5-i))+1,projection=ccrs.Orthographic(360-polelong, polelat))
    gl = ax1.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)

    ax1.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())
    
    # plt.scatter(sector2_lon,sector2_lat,transform=ccrs.PlateCarree(),c=sector2_loc,vmin=0,vmax=24,cmap='hsv',marker='.')

    # ax1.set_global()
    # 
    ax1.plot(north_plotting[3,:,3],north_plotting[3,:,2],transform=ccrs.PlateCarree(),linewidth=1,alpha=0.5)
    ax1.plot(north_plotting[13,:,3],north_plotting[13,:,2],transform=ccrs.PlateCarree(),linewidth=1,alpha=0.5,linestyle='--')
    ax1.plot(north_plotting[23,:,3],north_plotting[23,:,2],transform=ccrs.PlateCarree(),linewidth=1,alpha=0.5,linestyle='--')
    bbox_props1= dict(boxstyle="round,pad=0.15", fc="aliceblue", ec="gray", lw=1)
    bbox_props2= dict(boxstyle="circle,pad=0.15", fc="linen", ec="C2", lw=1)
    # bbox_props3= dict(boxstyle="circle,pad=0.15", fc="mintcream", ec="C3", lw=1)

    ax1.text(0.85, 0.9, lt_text[5-i] ,transform=ax1.transAxes, ha="center", va="center",bbox=bbox_props1, weight='bold',c='k',zorder=5)
    
    # txt1=ax1.text(s="08h",x=50, y=80, fontsize=10, fontweight='bold' ,fontstyle='italic',c='w',horizontalalignment='center', verticalalignment='center',zorder=4)


    for w in range(6):
        ww=int(w*60)
        wws=str(w*60)+'$^{\circ}$W'
        print(i,ww,wws)
        if w > 0:
            w1=ax1.text(ww, 60, wws , ha="center", va="center",transform=ccrs.PlateCarree(),c='w',zorder=4,fontsize='small')
            w1.set_path_effects([patheffects.withStroke(linewidth=1,foreground='k')])
    for w in range(3):
        w2=ax1.text(360-0, 60+w*10, str(60+w*10)+'$^{\circ}$N' , ha="center", va="center",transform=ccrs.PlateCarree(),c='w',zorder=4,fontsize='small')
        w2.set_path_effects([patheffects.withStroke(linewidth=1,foreground='k')])

    # xt1=ax1.text(10.5, 0.9, '08h' ,transform=ax1.transAxes, ha="center", va="center",zorder=5)

    # if i == 1:

        
    #     ax1cb = plt.subplot(3, 4, 4+4)

    #     cbar=fig.colorbar(cc,ax=ax1,location='right', pad=0.1, ticks=[0.1,0.7,1.3,1.9])
    #     cbar.ax.set_ylabel('Brightness')
    #     cbar.ax.yaxis.set_label_position("right")
       


    # if i == 5:

    #     ax1cb_blank = plt.subplot(3, 4, 4)

    #     # ax1cb.plot(position=[0,0.01,0,1])
    #     ax1cb.axis('off')
    #     ax1cb_blank.axis('off')
    #     # ax1cb.set_position([0,0,10,1])
    #     ax1.text(0.1, 0.1, 'a' ,transform=ax1.transAxes, ha="center", va="center",bbox=bbox_props2, weight='bold',c='k')
    
    
    ax2_base = plt.subplot(5, 4, (4*(5-i))+2,projection=ccrs.Orthographic(360-polelong, polelat))
    gl = ax2_base.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)

    # ax2_img = plt.subplot(5, 4, (4*(5-i))+1)
    ax2_chartBox = ax2_base.get_position()
    ax2_img = fig.add_axes([ax2_chartBox.x0, ax2_chartBox.y0, 
                 ax2_chartBox.width, 
                 ax2_chartBox.height], transform=ax2_base.transAxes, frameon=False) 
    ax2_img.set_axis_off()
    fig.set_facecolor("white")
    
    ax2_img.imshow(diff_x)

    ax2 = fig.add_axes([ax2_chartBox.x0, ax2_chartBox.y0, 
                      ax2_chartBox.width, 
                      ax2_chartBox.height], transform=ax2_base.transAxes,projection=ccrs.Orthographic(360-polelong, polelat), frameon=False) 

#     ax2 = plt.subplot(5, 4, (4*(5-i))+2,projection=ccrs.Orthographic(360-polelong, polelat))
#     gl = ax2.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)
#     # gl.xlocator = mticker.FixedLocator(np.arange(18)*20-180)
#     # gl.ylocator = mticker.FixedLocator(np.arange(9)*20-90)

#     mapmap_diff[mapmap_diff>1.4]=1.4
#     mapmap_diff[mapmap_diff<0.6]=0.6

#     cc2=ax2.contourf(lon2d, lat2d, mapmap_diff,transform=ccrs.PlateCarree(),levels=128,cmap='RdBu',vmax=maxrange,vmin=minrange) 

#     # if i == 1:

#     #     ax2cb = plt.subplot(3, 4, 3+4*2)
#     #     cbar=fig.colorbar(cc,ax=ax2cb,location='right', pad=0.1, ticks=[0.1,0.7,1.3,1.9])
#     #     cbar.ax.set_ylabel('Bright. Diff.')
#     #     cbar.ax.yaxis.set_label_position("right")


#     # for c in cc.collections:
#     #     c.set_edgecolor("face")
    gl = ax2.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)

    ax2.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())
    

    ax2.plot(north_plotting[3,:,3],north_plotting[3,:,2],transform=ccrs.PlateCarree(),linewidth=1,alpha=0.5)
    ax2.plot(north_plotting[13,:,3],north_plotting[13,:,2],transform=ccrs.PlateCarree(),linewidth=1,alpha=0.5,linestyle='--')
    ax2.plot(north_plotting[23,:,3],north_plotting[23,:,2],transform=ccrs.PlateCarree(),linewidth=1,alpha=0.5,linestyle='--')
    
    for w in range(6):
        ww=int(w*60)
        wws=str(w*60)+'$^{\circ}$W'
        print(i,ww,wws)
        if w > 0:
            w1=ax2.text(ww, 60, wws , ha="center", va="center",transform=ccrs.PlateCarree(),c='w',zorder=4,fontsize='small')
            w1.set_path_effects([patheffects.withStroke(linewidth=1,foreground='k')])
    for w in range(3):
        w2=ax2.text(360-0, 60+w*10, str(60+w*10)+'$^{\circ}$N' , ha="center", va="center",transform=ccrs.PlateCarree(),c='w',zorder=4,fontsize='small')
        w2.set_path_effects([patheffects.withStroke(linewidth=1,foreground='k')])

    
    
  
#     # if i == 1:

#     #     cbar=fig.colorbar(cc,ax=ax2,location='right', pad=0.1, ticks=[0.4,0.65,0.9,1.15,1.4])
#     #     # cbar=fig.colorbar(cc,ax=ax2,location='right', pad=0.1)
#     #     cbar.ax.set_ylabel('Bright. Diff.')
#     #     cbar.ax.yaxis.set_label_position("right")
    
#     # if i == 5:
#     #     ax2cb = plt.subplot(5, 4, 4+4*3)
#     #     ax2cb.axis('off')
#     #     ax2.text(0.1, 0.1, 'b' ,transform=ax2.transAxes, ha="center", va="center",bbox=bbox_props2, weight='bold',c='k')
       


#     phasemap=np.sum(mapfull[75+1*30:75+(5+1)*30,:,:],axis=0)/(30*5)/0.5e1
#     # phasemap[75+i*30:75+(i+1)*30,:]=phasemap[75+i*30:75+(i+1)*30,:]*1e1
#     phasemap[:,75+i*30:75+(i+1)*30]=phasemap[:,75+i*30:75+(i+1)*30]*0.5e1




    # ax5 = plt.subplot(1, 7, 8-i,projection=ccrs.Orthographic(360-polelong, polelat))
    ax5_base = plt.subplot(5, 4, (4*(5-i))+3,projection=ccrs.Orthographic(360-polelong, 0))
    gl = ax5_base.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)

    # ax5_img = plt.subplot(5, 4, (4*(5-i))+1)
    ax5_chartBox = ax5_base.get_position()
    ax5_img = fig.add_axes([ax5_chartBox.x0, ax5_chartBox.y0, 
                 ax5_chartBox.width, 
                 ax5_chartBox.height], transform=ax5_base.transAxes, frameon=False) 
    ax5_img.set_axis_off()
    fig.set_facecolor("white")
    
    ax5_img.imshow(lt_x)

    ax5 = fig.add_axes([ax5_chartBox.x0, ax5_chartBox.y0, 
                      ax5_chartBox.width, 
                      ax5_chartBox.height], transform=ax5_base.transAxes,projection=ccrs.Orthographic(360-polelong, 0), frameon=False) 


#     ax5 = plt.subplot(5, 4, (4*(5-i))+3,projection=ccrs.Orthographic(360-polelong, 0))
#     gl = ax5.gridlines(crs=ccrs.PlateCarree(), linewidth=1, color='grey', alpha=0.95, linestyle='dotted', draw_labels=False)
#     # gl.xlocator = mticker.FixedLocator(np.arange(18)*20-180)
#     # gl.ylocator = mticker.FixedLocator(np.arange(9)*20-90)

#     cc=ax5.contourf(lon2d, lat2d, phasemap,transform=ccrs.PlateCarree(),levels=128,cmap='afmhot', norm=PowerNorm(gamma=0.5, vmin=minint, vmax=maxint) )

#     for c in cc.collections:
#         c.set_edgecolor("face")


#     # ax5.set_extent([0, 360, 50, 90], crs=ccrs.PlateCarree())
    
#     # plt.scatter(sector2_lon,sector2_lat,transform=ccrs.PlateCarree(),c=sector2_loc,vmin=0,vmax=24,cmap='hsv',marker='.')

    ax5.set_global()
#     # 
#     # ax5.plot(north_plotting[3,:,3],north_plotting[3,:,2],transform=ccrs.PlateCarree(),linewidth=1,alpha=0.5)
#     # ax5.plot(north_plotting[13,:,3],north_plotting[13,:,2],transform=ccrs.PlateCarree(),linewidth=1,alpha=0.5,linestyle='--')
#     # ax5.plot(north_plotting[23,:,3],north_plotting[23,:,2],transform=ccrs.PlateCarree(),linewidth=1,alpha=0.5,linestyle='--')

    ax5.plot(np.zeros(30)+75+(6-i)*30,np.arange(30)*6-90,transform=ccrs.PlateCarree(),linewidth=1,linestyle='--',color='w')
    ax5.plot(np.zeros(30)+75+(6-i)*30+30,np.arange(30)*6-90,transform=ccrs.PlateCarree(),linewidth=1,linestyle='--',color='w')

#     # # for w in range(6):
#     # #     ww=int(w*60)
#     # #     wws=str(w*60)+'$^{\circ}$W'
#     # #     print(i,ww,wws)
#     # #     if w > 0:
#     # #         w1=ax5.text(ww, 60, wws , ha="center", va="center",transform=ccrs.PlateCarree(),c='w',zorder=4,fontsize='small')
#     # #         w1.set_path_effects([patheffects.withStroke(linewidth=1,foreground='k')])
#     # # for w in range(5):
#     # #     w2=ax5.text(360-0, 15+w*15, str(15+w*15)+'$^{\circ}$N' , ha="center", va="center",transform=ccrs.PlateCarree(),c='w',zorder=4,fontsize='small')
#     # #     w2.set_path_effects([patheffects.withStroke(linewidth=1,foreground='k')])
#     # #     w2s=ax5.text(360-0, w*15-75, str(15+(5-w)*15)+'$^{\circ}$S' , ha="center", va="center",transform=ccrs.PlateCarree(),c='w',zorder=4,fontsize='small')



    if i == 5:

 
          # ax1cb.set_position([0,0,10,1])
        ax1.text(0.1, 0.1, 'a' ,transform=ax1.transAxes, ha="center", va="center",bbox=bbox_props2, weight='bold',c='k')
        ax2.text(0.1, 0.1, 'b' ,transform=ax2.transAxes, ha="center", va="center",bbox=bbox_props2, weight='bold',c='k')
        ax5.text(0.1, 0.1, 'c' ,transform=ax5.transAxes, ha="center", va="center",bbox=bbox_props2, weight='bold',c='k')
 
    

    
#         # if i == 4:

#         #    # ax1cb = plt.subplot(3, 4, 4)
#         #    cbar=fig.colorbar(cc1,ax=ax5,location='left', pad=0.1, ticks=[0.1,0.7,1.3,1.9])
#         #    cbar.ax.set_ylabel('Brightness')
#         #    cbar.ax.yaxis.set_label_position("right")

#         # for c in cc1.collections:
#         #    c.set_edgecolor("face")

#         # if i == 2:

#         #    # ax2cb = plt.subplot(3, 4, 4*3)
#         #    cbar=fig.colorbar(cc2,ax=ax5,location='left', pad=0.1, ticks=[0.1,0.7,1.3,1.9])
#         #    cbar.ax.set_ylabel('Bright. DIff.')
#         #    cbar.ax.yaxis.set_label_position("right")

#         # for c in cc2.collections:
#         #   c.set_edgecolor("face")

        
#     # # if i == 1:

#     # #     cbar=fig.colorbar(cc,ax=ax5,location='right', pad=0.1)
#     # #     cbar.ax.set_ylabel('Brightness')
#     # #     cbar.ax.yaxis.set_label_position("right")
       

#     # #     # cbar.remove()
#     # #     # cbar.set_visible(False) # doesnt work could do cbar.outline.set_visible(False)
#     # #     # cbar.outline.set_visible(False)
#     # #     # cbar.solids.set_visible(False) # leaves text and ticks?

#     # #     cbar.ax.set_visible(False)


#     print(i)




ax1cb = plt.subplot(3, 5, 5)


cbar=fig.colorbar(cc1,ax=ax1cb,location='left', pad=0.1, ticks=[0.1,0.7,1.3,1.9])
cbar.ax.set_ylabel('Average Auroral Brightness')
cbar.ax.yaxis.set_label_position("right")

for c in cc1.collections:
    c.set_edgecolor("face")


ax1cb.axis('off')

ax2cb = plt.subplot(3, 5, 5*3)
# cbar=fig.colorbar(cc2,ax=ax2cb,location='left', pad=0.1, ticks=[0.6,0.8,1.0,1.2,1.4])
cbar=fig.colorbar(cc2,ax=ax2cb,location='left', pad=0.1, ticks=np.arange(minrange,maxrange,0.2))
cbar.ax.set_ylabel('Bright. DIff.')
cbar.ax.yaxis.set_label_position("right")

for c in cc2.collections:
      c.set_edgecolor("face")

ax2cb.axis('off')

medianstr = ""
if median_switch == 'True':
    medianstr = "_median2"

fig.savefig('asd2'+medianstr+'.pdf', dpi=300, facecolor='white') 
